'use strict';

const Service = require('egg').Service;
const fs = require('fs');
const sendToWormhole = require('stream-wormhole');
const awaitWriteStream = require('await-stream-ready').write;
const { resolve } = require('path');

class UploadService extends Service {
  async getUploadFile(fileObj) {
    const { ctx } = this;
    const file = fs.readFileSync(fileObj.filepath);
    console.log(file);
    fs.writeFileSync(resolve(__dirname, `../public/upload/${fileObj.filename}`), file);
    ctx.status = 200;
    return { code: 0, message: '上传成功', data: {} };
  }

  async getUploadStream(stream) {
    const { ctx } = this;
    const remoteFileStrem = fs.createWriteStream(resolve(__dirname, `../public/upload/${stream.filename}`));
    try {
      // 以管道方式写入流
      await awaitWriteStream(stream.pipe(remoteFileStrem));
    } catch (error) {
      await sendToWormhole(stream);
      ctx.status = 500;
      return { code: 1, message: '上传失败', data: {} };
    }
    ctx.status = 200;
    return { code: 0, message: '上传成功', data: {} };
  }
}
module.exports = UploadService;
